package com.oauth.auth.interceptors;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.google.appengine.api.users.User;
import com.google.gwt.user.server.rpc.RPC;
import com.oauth.components.client.rpc.exception.SessionExpiredException;
import com.oauth.logging.OAuthLogger;
import com.oauth.service.members.beans.Member;
import com.oauth.service.members.service.MemberService;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	private MemberService mMemberService;
	private static final OAuthLogger log = OAuthLogger.getLogger("LoginInterceptor");
	private static final String CHARSET_UTF8 = "UTF-8";
	private static final String CONTENT_TYPE_TEXT_PLAIN_UTF8 = "text/plain; charset=utf-8";

	public boolean preHandle(HttpServletRequest pRequest, HttpServletResponse pResponse,
			Object pCommand) throws Exception {

		User user = (User) pRequest.getAttribute("user");
		if (user == null) {
			// NOTE: This must be POST url.
			String payload = RPC.encodeResponseForFailure(null, new SessionExpiredException(
					"Session Expired"));
			writeResponse(pRequest, pResponse, payload);
			return false;
		}
		log.debug("Inside login interceptor:" + user.getEmail());

		Member member = getMemberService().getMember(user.getEmail(), true);
		member.setNickName(user.getNickname());

		pRequest.setAttribute("member", member);
		return true;
	}

	private void writeResponse(HttpServletRequest request, HttpServletResponse response,
			String responsePayload) throws IOException {
		byte[] reply = responsePayload.getBytes(CHARSET_UTF8);
		String contentType = CONTENT_TYPE_TEXT_PLAIN_UTF8;
		// Send the reply.
		response.setContentLength(reply.length);
		response.setContentType(contentType);
		response.setStatus(HttpServletResponse.SC_OK);
		response.getOutputStream().write(reply);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.web.servlet.handler.HandlerInterceptorAdapter#postHandle
	 * (javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse, java.lang.Object,
	 * org.springframework.web.servlet.ModelAndView)
	 */
	public void postHandle(HttpServletRequest pRequest, HttpServletResponse pResponse,
			Object pHandler, ModelAndView pModelAndView) throws Exception {
		// Populate environment urls.
		/*
		 * Member member = (Member)pRequest.getAttribute("member");
		 * pModelAndView.addObject("member",member);
		 */
	}

	public MemberService getMemberService() {
		return mMemberService;
	}

	@Autowired
	public void setMemberService(MemberService pMemberService) {
		mMemberService = pMemberService;
	}

}